package com.ncucoder.soms.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件上传/下载的工具类
 *
 * @author <a href="https://www.ncucoder.com">hsowan</a>
 * @date 2019-07-11
 **/
public class FileUtils {

    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    private static String dir = PropertyUtils.properties.getProperty("file.dir");

    public static String upload(MultipartFile file) {

        FileOutputStream out = null;
        String filename = file.getOriginalFilename();

        if (filename == null) {
            return null;
        }

        File f = new File(dir);
        // 判断文件存储目录是否存在, 不存在则创建
        if(!f.exists() || !f.isDirectory()){
            // 如果创建目录失败, 直接返回null
            if (!f.mkdirs()) {
                logger.error("创建目录失败");
                return null;
            }
        }

        // 同名文件上传处理
        // ha.jpg
        // 再次上传: ha(1).jpg
        int count = 1;
        int lastDotIndex;
        int lastLeftBracketIndex;
        String prefix;
        String suffix;
        while (true) {
            File uploadFile = new File(dir + filename);
            if (uploadFile.exists() && uploadFile.isFile()) {
                lastDotIndex = filename.lastIndexOf(".");
                suffix = filename.substring(lastDotIndex + 1);
                if (count == 1) {
                    prefix = filename.substring(0, lastDotIndex);

                } else {
                    lastLeftBracketIndex = filename.lastIndexOf("(");
                    prefix = filename.substring(0, lastLeftBracketIndex);
                }
                filename = prefix + "(" + count + ")." + suffix;
                count++;

            } else {
                break;
            }
        }

        try {
            out = new FileOutputStream(dir + filename);
            out.write(file.getBytes());
            out.flush();
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
        return filename;
    }

    /**
     * 判断文件是否存在
     *
     * @param filename
     * @return
     */
    public static File isExisted(String filename) {

        File file = new File(dir + filename);
        if (file.exists() && file.isFile()) {
            return file;
        }
        return null;
    }

}
